package dataImport.action;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import dataImport.action.abstracts.AbstractEntityReader;
import dataImport.action.helper.UnityGuardian;
import dataImport.action.manager.EntityReaderManager;
import dataImport.exception.DuplicateAttributeException;
import dataImport.exception.MissingAttributeException;
import dataImport.exception.UniquenessRestrictionViolatedException;
import dataImport.model.Command;
import dataImport.model.abstracts.AbstractEntity;


public class CommandReader extends AbstractEntityReader {

	private static final long serialVersionUID = 3166789661223136258L;

	public static final String ENTITY_NAME = "command";

	private static final String ATTRIBUTE_PATTERN = "pattern";

	private UnityGuardian patternUniqueKey;

	public CommandReader(final EntityReaderManager entityReaderManager) {
		super(entityReaderManager);
		this.patternUniqueKey = new UnityGuardian();
	}

	@Override
	protected AbstractEntity createEntity(final Element element) {
		final String id = element.getAttribute(ATTRIBUTE_ID);
		final String pattern = element.getAttribute(ATTRIBUTE_PATTERN);

		this.verifyRestrictions(id, pattern);

		return new Command(id, pattern);
	}

	@Override
	public void read(final Document document) {
		this.read(CommandReader.ENTITY_NAME, document);
	}

	protected final void verifyRestrictions(final String id, final String pattern) {
		super.verifyRestrictions(id);

		try {
			this.patternUniqueKey.ensureUniqueness(pattern);
		}
		catch (UniquenessRestrictionViolatedException e) {
			throw new DuplicateAttributeException("pattern", pattern);
		}

		if (pattern.isEmpty()) {
			throw new MissingAttributeException(ATTRIBUTE_PATTERN);
		}
	}
}
